package org.ns.basics.commons.localex;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

public class LocaleService {

	public static final LocaleService EMPTY = new LocaleService(null, null, true);

	private LocaleMap localeMap;
	private Locale defaultLocale;

	private String path;
	private LocaleFileLoader localeFileLoader;
	private boolean ignoreCase;

	private LocaleValueFormat localeValueFormat = new GlLocaleValueFormat();

	public LocaleService(String path, LocaleFileLoader localeFileLoader, boolean ignoreCase) {
		this.path = path;
		this.localeFileLoader = localeFileLoader;
		this.ignoreCase = ignoreCase;
		this.reset();
	}

	public void setLocaleValueFormat(LocaleValueFormat localeValueFormat) {
		this.localeValueFormat = localeValueFormat;
	}

	public void reset() {
		if (path != null && localeFileLoader != null) {
			try {
				URL url = getURL(path);
				try (InputStream in = url.openStream()) {
					localeMap = localeFileLoader.parse(in, path, ignoreCase);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void setDefaultLocale(Locale defaultLocale) {
		this.defaultLocale = defaultLocale;
	}

	private URL getURL(String path) {
		if (path.startsWith("classpath:")) {
			String file = path.substring("classpath:".length());
			return getClass().getClassLoader().getResource(file);
		} else {
			try {
				return new File(path).toURI().toURL();
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			}
		}
	}

	public String get(Locale locale, String key, Object... args) {
		if (localeMap == null) {
			return null;
		}
		String message = localeMap.get(locale, key);
		if (message == null && defaultLocale != null) {
			message = localeMap.get(defaultLocale, key);
		}
		if (message != null && message.length() > 0) {
			message = localeValueFormat.format(message, args);
		}
		return message;
	}

}
